package com.xt.mes.config.filter;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * Version: V1.0
 * Last Update Time:
 */
public class MyAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
            throws Exception {
        System.out.println("连接器作业"+response.toString());
        WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //1.获取Subject,通过Subject可以获取到当前登入用户的信息,与数据库总
        Subject subject = this.getSubject(request, response);
        //2.mappedValue 就是配置到ShiroFilterFactoryBean中的拦截器Map集合中的value中的数组
        //例如配置filterMap.put("/接口访问路径3","role[admin:aaa]")时mapValue中就可以拿到admin与aaa
        String[] rolesArray = (String[])((String[])mappedValue);
        if (rolesArray != null && rolesArray.length != 0) {
            Set<String> roles = CollectionUtils.asSet(rolesArray);
            //3.默认是 subject.hasAllRoles(roles) 该方法时比对所有
            //也就是当前访问该接口的用户要同时持有roles集合中所有权限才可以访问
            //修改为只要有一个即可
            return roles.stream().anyMatch(role -> subject.hasRole(role));
        } else {
            //如果为空,说明没有配置对应的角色,直接放行
            return true;
        }
    }

}
